package ch.fusun.baron.clientapp.login;

import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import ch.fusun.baron.client.rmi.ClientService;
import ch.fusun.baron.clientapp.messages.Messages;

/**
 * Dialog for login
 */
public class LoginDialog extends TitleAreaDialog {

	private Text username;
	private Text password;
	private final ClientService gameClient;

	/**
	 * Constructor
	 * 
	 * @param parentShell
	 *            The parent shell
	 * @param clientService
	 *            The game client
	 */
	public LoginDialog(Shell parentShell, ClientService clientService) {
		super(parentShell);
		this.gameClient = clientService;
	}

	@Override
	protected Control createDialogArea(Composite parent) {
		Composite area = new Composite(parent, SWT.NONE);
		area.setLayout(new GridLayout(2, false));
		area.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));

		new Label(area, SWT.NONE).setText(Messages.LoginDialog_UserName);
		username = new Text(area, SWT.BORDER);
		username.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));

		new Label(area, SWT.NONE).setText(Messages.LoginDialog_Password);
		password = new Text(area, SWT.BORDER | SWT.PASSWORD);
		password.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false));

		new Label(area, SWT.NONE).setText(Messages.LoginDialog_NoAccountQuestion);
		Button newAccount = new Button(area, SWT.PUSH);
		newAccount.setText(Messages.LoginDialog_CreateAccount);
		newAccount.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				new CreateAccountDialog(getShell(), gameClient).open();
			}
		});

		return area;
	}

	/**
	 * @return The user name
	 */
	public String getUsername() {
		return username.getText();
	}

	/**
	 * @return The password
	 */
	public String getPassword() {
		return password.getText();
	}

	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		((GridLayout) parent.getLayout()).numColumns++;

		Button button = new Button(parent, SWT.PUSH);
		button.setText(Messages.LoginDialog_Login);
		button.setFont(JFaceResources.getDialogFont());
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				gameClient.login(username.getText(), password.getText());
				close();
			}
		});
	}

}
